import 'package:flutter/material.dart';
import 'dart:async';

import 'package:flutter/services.dart';
import 'package:iamgeqr_flutter_plugin/iamgeqr_flutter_plugin.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String _platformVersion = 'Unknown';
  final _iamgeqrFlutterPlugin = IamgeqrFlutterPlugin();
  final GlobalKey<ScaffoldMessengerState> _messengerKey = GlobalKey<ScaffoldMessengerState>();

  @override
  void initState() {
    super.initState();
    initPlatformState();
  }

  // Platform messages are asynchronous, so we initialize in an async method.
  Future<void> initPlatformState() async {
    String platformVersion;
    // Platform messages may fail, so we use a try/catch PlatformException.
    // We also handle the message potentially returning null.
    try {
      platformVersion =
          await _iamgeqrFlutterPlugin.getPlatformVersion() ?? 'Unknown platform version';
    } on PlatformException {
      platformVersion = 'Failed to get platform version.';
    }

    // If the widget was removed from the tree while the asynchronous platform
    // message was in flight, we want to discard the reply rather than calling
    // setState to update our non-existent appearance.
    if (!mounted) return;

    setState(() {
      _platformVersion = platformVersion;
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      scaffoldMessengerKey: _messengerKey,
      home: Scaffold(
        appBar: AppBar(
          title: const Text('测试页面'),
        ),
        body: Padding(
          padding: const EdgeInsets.all(16),
          child: Column(
            children: [
              Text('当前系统: $_platformVersion'),
              const SizedBox(height: 12),
              SizedBox(
                width: double.infinity,
                child: OutlinedButton.icon(
                  onPressed: _refreshPlatformVersion,
                  icon: const Icon(Icons.refresh),
                  label: const Text('重新获取平台版本'),
                ),
              ),
              const SizedBox(height: 12),
              SizedBox(
                width: double.infinity,
                child: ElevatedButton(
                  onPressed: _isScanning ? null : _scanImageQR,
                  child: _isScanning
                      ? Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: const [
                            SizedBox(
                              height: 18,
                              width: 18,
                              child: CircularProgressIndicator(strokeWidth: 2),
                            ),
                            SizedBox(width: 8),
                            Text('识别中...'),
                          ],
                        )
                      : const Text('从图片选择二维码并识别'),
                ),
              ),
              const SizedBox(height: 16),
              if (_scanResult != null) ...[
                Align(
                  alignment: Alignment.centerLeft,
                  child: Text(
                    '识别结果',
                    style: Theme.of(context).textTheme.titleMedium,
                  ),
                ),
                const SizedBox(height: 8),
                Card(
                  elevation: 2,
                  child: Padding(
                    padding: const EdgeInsets.all(12.0),
                    child: SelectableText(
                      _scanResult!,
                      style: const TextStyle(fontSize: 14),
                    ),
                  ),
                ),
                const SizedBox(height: 8),
                Row(
                  children: [
                    ElevatedButton.icon(
                      onPressed: _copyResult,
                      icon: const Icon(Icons.copy, size: 16),
                      label: const Text('复制'),
                    ),
                    const SizedBox(width: 8),
                    OutlinedButton.icon(
                      onPressed: () => setState(() => _scanResult = null),
                      icon: const Icon(Icons.clear, size: 16),
                      label: const Text('清空'),
                    ),
                  ],
                ),
              ],
            ],
          ),
        ),
      ),
    );
  }

  String? _scanResult;
  bool _isScanning = false;

  Future<void> _scanImageQR() async {
    if (_isScanning) return;
    setState(() {
      _isScanning = true;
    });
    try {
      final result = await _iamgeqrFlutterPlugin.imageScanQr();
      if (!mounted) return;
      setState(() {
        final trimmed = result?.trim();
        _scanResult = (trimmed == null || trimmed.isEmpty) ? '未识别到有效二维码' : trimmed;
      });
    } on PlatformException catch (e) {
      if (!mounted) return;
      setState(() {
        _scanResult = '扫描失败: ${e.message ?? e.code}';
      });
    } catch (e) {
      if (!mounted) return;
      setState(() {
        _scanResult = '扫描失败: $e';
      });
    } finally {
      if (mounted) {
        setState(() {
          _isScanning = false;
        });
      }
    }
  }

  void _copyResult() {
    if (_scanResult == null || _scanResult!.isEmpty) return;
    Clipboard.setData(ClipboardData(text: _scanResult!));
    _messengerKey.currentState?.showSnackBar(
      const SnackBar(content: Text('已复制到剪贴板')),
    );
  }

  Future<void> _refreshPlatformVersion() async {
    try {
      final ver = await _iamgeqrFlutterPlugin.getPlatformVersion() ?? 'Unknown platform version';
      if (!mounted) return;
      setState(() {
        _platformVersion = ver;
      });
      _messengerKey.currentState?.showSnackBar(
        SnackBar(content: Text('平台版本: $ver')),
      );
    } on PlatformException catch (e) {
      _messengerKey.currentState?.showSnackBar(
        SnackBar(content: Text('获取平台版本失败: ${e.message ?? e.code}')),
      );
    } catch (e) {
      _messengerKey.currentState?.showSnackBar(
        SnackBar(content: Text('获取平台版本失败: $e')),
      );
    }
  }
}
